/* 
 * File:   ShowFindUpdateCPO.cpp
 * Author: Topher
 * 
 */

#include "ShowFindUpdateCPO.h"

string ShowFindUpdateCPO::show(vector<Customer> customers) 
{
    stringstream ss;
    
    sort(customers.begin(),customers.end(), compareCustomer);
    
    for(int x=0;x<customers.size();x++)
    {
        ss<<customers.at(x).get_cust_name()<<" | ID = "<<customers.at(x).get_cust_id()
			<<" | Address = "
			<<customers.at(x).get_cust_addr().get_building_id() 
			<< " " << customers.at(x).get_cust_addr().get_street_id() 
			<< " " << customers.at(x).get_cust_addr().get_zip_id() 
			<< " " << endl;
        ss<<endl;
    }
        string output=ss.str();
        return output;
}

double ShowFindUpdateCPO::find(int cust, vector<Cart> cart, vector<Cart_item> item, vector<Product> prod)
{
    vector<Cart> search;
    vector<Cart_item> searchtwo;
    double total=0;
    //  Finds customer's carts and inserts into "search" vector.
    for(int x=0;x<cart.size();x++)
    {
        if(cart.at(x).get_cust_id()==cust)
        {
            search.push_back(cart.at(x));
        }
    }
    
    //  Searches Cart_Items for matches and stores their id.
    for(int y=0;y<search.size();y++)
    {
        for(int x=0;x<item.size();x++)
            if(item.at(x).get_cart_id()==search.at(y).get_cart_id())
                searchtwo.push_back(item.at(x));
    }
    
    //  Finds prices and quantity and adds subtotal to total.
    for(int x=0;x<searchtwo.size();++x)
    {
        double sub=get_price_by_id(prod, searchtwo.at(x).get_prod_id())*searchtwo.at(x).get_prod_qty();
        total+=sub;
    }
    
	return total;
}

void ShowFindUpdateCPO::update(Customer cust, vector<Customer> &customers)
{
    bool check=false;
    
    for(int x=0;x<customers.size();x++)
    {
        if(customers.at(x).get_cust_id()==cust.get_cust_id())
        {
                check=true;
                break;
        }
    }
    
    if(check)
    {
        cout<<"Customer already exists"<<endl;
    }
    else
    {
        customers.push_back(cust);
    }
}

bool ShowFindUpdateCPO::compareCustomer(Customer a, Customer b)
{
    return(a.get_cust_name() < b.get_cust_name());
}

double ShowFindUpdateCPO::get_price_by_id(vector<Product> prod, int id)
{
    double price=0;
    
    for(int x=0;x<prod.size();x++)
    {
        if(prod.at(x).get_prod_id()==id)
        {
                price=prod.at(x).get_prod_price();
                break;
        }
    }
    return price;
}